<template>
  <div class="form-standard" v-if="value">
    <div class="radio-select">
      <el-radio-group v-model="fieldValue.hasSpecs" @change="changeSelect">
        <el-radio :label="1">{{ $t('common.base.yes') }} </el-radio>
        <el-radio :label="0">{{ $t('common.base.no') }}</el-radio>
      </el-radio-group>
      
    </div>
    <div v-if="fieldValue.hasSpecs == '0'">
      <form-item :label="$t('goods.component.specificationDesc')">
        <el-input v-model="fieldValue.standard" @change="changeStandard"></el-input>
      </form-item> 
    </div>
    <div v-else>
      <form-item :label="$t('goods.component.productSpecifications')">
        <div v-for="(specification, index) in fieldValue.specifications" :key="index">
      <el-select
        v-model="specification.name"
        @change="fieldNameChange(specification, index)"
        :placeholder="$t('goods.placeHolder.selectProductSpec')"
        style="width:150px;margin:0 10px 10px 0;"
      >
        <el-option
          v-for="(item, index) in allSpecificationList"
          :key="index"
          :label="item.name"
          :value="item.name"
          :disabled="item.disabled"
        >
        </el-option>
      </el-select>
      <el-select
        v-model="specification.selectItem"
        :placeholder="$t('goods.placeHolder.selectSpecValue')"
        multiple
        @change="changeSpecifications"
      >
        <el-option
          v-for="(item, index) in getValueOptions(specification.name)"
          :key="item"
          :label="item"
          :value="item"
        >
        </el-option>
      </el-select>
      <i
        class="iconfont icon-delete"
        @click="delSpecification(index)"
        v-if="fieldValue.specifications.length > 1"
      ></i>
    </div>
        <el-button plain @click="addSpecification">{{ $t('goods.component.addSpecifications') }}</el-button>
        <div class="no-setting-tip">{{ $t('goods.component.toSetting') }}<span class="jump-style" @click="toShopSetting">{{ $t('order.setting.mail') }}</span></div>
      </form-item>
      <form-item :label="$t('goods.component.specsDetails')" v-if="pageData && pageData.length">
        <div>
          <el-table :data="pageData" border style="margin-top:10px;">
            <el-table-column
              v-for="(column, index) in columns"
              :key="`${index}_index`"
              :label="column.name"
              :prop="column.fieldName"
              show-overflow-tooltip
              :fixed="column.fixed ? 'right' : false"
              :minWidth="column.minWidth || 'auto'"
            >
              <template slot-scope="scope">
                <el-input v-if="column.fieldName=='serialNumber'" v-model="scope.row[column.fieldName]" :placeholder="$t('common.placeholder.input2')"></el-input>
                <el-input-number v-else-if="column.fieldName =='salePrice'" v-model="scope.row[column.fieldName]" :placeholder="$t('common.placeholder.input2')"  controls-position="right" :min="0.01" @change="priceChange"></el-input-number>
                <el-input-number v-else-if="column.fieldName=='inventory'" v-model="scope.row[column.fieldName]" :placeholder="$t('common.placeholder.input2')"  controls-position="right" :min="0" @change="inventoryChange"></el-input-number>
                <span v-else>{{ scope.row[column.name] }}</span>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            layout="prev, pager, next"
            background
            :current-page="currentPage"
            :page-size="10"
            :total="total"
            @current-change="changePage">
          </el-pagination>
        </div>
      </form-item>
    </div>
  </div>
</template>

<script>
import FormMixin from '@src/component/form/mixin/form';
import { openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { querySpecsList } from '@src/api/LinkcApi';
import EventBus from '@src/util/eventBus';
import _ from "lodash";
export default {
  name: 'form-standard-desc',
  mixins: [FormMixin],
  props: {
    value: {
      type: Object,
    }
  },
  data() {
    return {
      arr: [],
      columns: [],
      fixedColumns: ['serialNumber', 'salePrice', 'inventory'],
      pageData:[],
      currentPage: 1,
      fieldValue: {
        hasSpecs: 0,
        standard: '',
        specifications: [],
        specsList: []
      },
      isFirstPage: true
    }
  },
  
  computed: {
     // 所有规格组
    allSpecificationList() {
      let formatArr = (this.arr || []).map(item => {
        let selected = (this.fieldValue.specifications || []).find(v => v.name == item.name)
        this.$set(item, 'disabled', (!_.isEmpty(selected)))
        return item
      })
      return formatArr
    },
    // 所有规格名
    allNames() {
      return (this.arr || []).map(item => {
        return item.name;
      });
    },
    // 已选择规格名
    hasSelectNames() {
      return (this.fieldValue.specifications || []).filter(item => {return item.name}).map(item => {
        return item.name;
      });
    },
    // 已选择并且有值的规格
    hasSelectNamesWithValues() {
      return (this.fieldValue.specifications || []).filter(item => {return item.name && item.selectItem && item.selectItem.length > 0})
    },
    total(){
      return this.fieldValue.specsList.length
    }
  },
  mounted() {
    this.getSpecsList()
  },
  methods: {
    getSpecsList() {
      querySpecsList().then(res => {
          if(res.code != 200) return this.$message.error(res.msg);
          this.arr = (res.data || []).map(item => {
            return {
              name: item.specsName,
              fieldName: item.fieldName,
              valueList: item.specsValue
            }
          })
      }).catch(err => {
          this.$message.error(res.msg);
      })
    },
    fieldNameChange(items, index) {
      items.selectItem = []
      this.arr.forEach(item => {
        if(item.name == items.name) {
          items.valueList = item.valueList
        }
      })
      this.update(this.fieldValue)
    },
    changeStandard() {
      this.update(this.fieldValue)
    },
    changeSelect(val) {
      this.update(this.fieldValue)
      this.priceChange()
      this.inventoryChange()
    },
    cartesianProduct(arr) {
      return arr.reduce(function(a,b){
          return a.map(function(x){
              return b.map(function(y){
                  return x.concat([y]);
              })
          }).reduce(function(a,b){ return a.concat(b) },[])
      }, [[]])
    },
    descartes() {
      let data = []
      let values = this.cartesianProduct(this.hasSelectNamesWithValues.map(item => item.selectItem))
      let names = this.hasSelectNamesWithValues.map(item => item.name)
      values.forEach(value=>{
        let item = {}
        names.forEach((name,index)=>{
          this.$set(item, name, value[index] )
          item.serialNumber = item.serialNumber ||  ''
          item.salePrice = 0.01
          item.inventory = 0
          item.valueList = value
        })
        data.push(item)
      })
      let mapData = data.map(item => {
        this.originData?.forEach((v,key) => {
          if(this.compareArray(item.valueList, key)) {
            item = v
          }
        })
        return item
      })
      return mapData
      
    },
    compareArray(a, b) {
      console.log(a, b)
      if(a && b) {
        a = a.sort()
        b = b.sort()
      }
      return _.isEqual(a,b)
    },
    changePage(val){
      this.pageData = this.fieldValue.specsList.slice((val-1)*10, val*10)
    },
    getColumns(val) {
      return (val?.specifications || [])
        .map(item => {
          return { name: item.specsName, fieldName: item.fieldName };
        })
        .concat([
          { name: this.$t('common.base.serialNumber'), fieldName: 'serialNumber', fixed: true, minWidth: 156 },
          { name: this.$t('common.base.price'), fieldName: 'salePrice', fixed: true, minWidth: 156 },
          { name: this.$t('common.form.preview.sparepart.label4'), fieldName: 'inventory', fixed: true, minWidth: 156 },
        ]) || []
    },
    update(newValue) {
      let oldValue = null
      this.$emit('update', { newValue, oldValue, field: this.field });
      this.$emit('input', newValue);
    },
    getNameOptions(currentName) {
      let names = this.allNames.filter(item => {
        return this.hasSelectNames.indexOf(item) == -1;
      });
      return names;
    },
    getValueOptions(currentName) {
      return (
        (this.allSpecificationList || []).find(item => {
          return item.name == currentName;
        })?.valueList || []
      );
    },
    delSpecification(index) {
      this.fieldValue.specifications.splice(index, 1);
      this.changeSpecifications()
      this.update(this.fieldValue)
    },
    addSpecification() {
      if(this.fieldValue.specifications.length >= 3) {
        return this.$message.error(this.$t('goods.limit.specsLimit'));
      }
      this.fieldValue.specifications.push({ name: '', selectItem: [] });
    },
    // 规格值变动
    changeSpecifications() {
      this.columns = this.fieldValue.specifications
        .map(item => {
          let select = this.arr.find(v => v.name == item.name) || {}
          return { 
            name: item.name, 
            fieldName: select?.fieldName || '',
            valueList: select.valueList
          };
        })
        .concat([
          { name: this.$t('common.base.serialNumber'), fieldName: 'serialNumber', fixed: true, minWidth: 156 },
          { name: this.$t('common.base.price'), fieldName: 'salePrice', fixed: true, minWidth: 156 },
          { name: this.$t('common.form.preview.sparepart.label4'), fieldName: 'inventory', fixed: true, minWidth: 156 },
        ]);
      this.getDefaultData();
      this.update(this.fieldValue)
      this.priceChange()
      this.inventoryChange()
    },
    getDefaultData() {
      this.fieldValue.specsList = this.descartes()
      this.pageData = this.fieldValue.specsList.slice(0,10)
      this.currentPage = 1
    },
    toShopSetting() {
      let fromId = window.frameElement.getAttribute('id');

      openAccurateTab({
        type: PageRoutesTypeEnum.PageShopManagementSetting,
        fromId
      })
    },
    priceChange() {
      let arr = this.fieldValue?.specsList?.filter(item => item?.salePrice).map(v => v?.salePrice) || []
      let min = 0
      let max = 0
      if(arr.length) {
        min = Math.min(...arr)
        max = Math.max(...arr)
      }
      let str = `${min}~${max}`
      EventBus.$emit('priceChange', str)
    },
    inventoryChange(){
      let totalInventory = 0
      this.fieldValue?.specsList?.forEach(item => {
        if(item.inventory) {
          totalInventory += item.inventory
        }
      })
      EventBus.$emit('inventoryChange', totalInventory)
    },
  },
  watch: {
    value: {
      handler(val){
        Object.assign(this.fieldValue, val);
        if(this.isFirstPage && val?.specsList) {
          this.pageData = (this.fieldValue?.specsList ||  []).slice(0,10)
          const map = new Map()
          this.fieldValue.specsList.forEach(v => {
            let key = [];
            v?.specsInfo?.forEach(f => {
              key.push(f.specsInfoValue)
            })
            map.set(key, v)
          })
          this.originData = map
          this.priceChange()
          this.isFirstPage = false
        }
        this.columns = (this.fieldValue?.specifications || [])
        .map(item => {
          return { name: item.name, fieldName: item.fieldName };
        })
        .concat([
          { name: this.$t('common.base.serialNumber'), fieldName: 'serialNumber', fixed: true, minWidth: 156 },
          { name: this.$t('common.base.price'), fieldName: 'salePrice', fixed: true, minWidth: 156 },
          { name: this.$t('common.form.preview.sparepart.label4'), fieldName: 'inventory', fixed: true, minWidth: 156 },
        ]) || []
      },
      deep:true,
      immediate:true
    },
  },

}
</script>

<style lang="scss">
.form-standard {
  width: 100%;
  .radio-select {
    margin-bottom: 12px;
  }
  input {
    width: 100%;

    &:disabled {
      -webkit-text-fill-color: #BFBFBF;
      border-color: #D9D9D9;
      background-color: #f5f5f5;

      &:hover {
        border-color: #D9D9D9;
      }
    }
  }
  .el-select {
    width: 40%;
  }
  .add-button {
    display: inline-block;
  }
  .item-wrap {
    width: 100%;
    display: flex;
    align-items: center;
    margin-bottom: 12px;
    .specs-select {
      width: 150px;
    }
    .value-select {
      flex: 1;
      margin: 0 10px 0 8px
    }
  }
  .no-setting-tip {
    margin-top: 12px;
    color: #8c8c8c;
    font-size: 12px;
    .jump-style {
      color: $color-primary-light-6;
    }
  }
  
}
</style>
